package com.jtask.mvp.view;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import roboguice.activity.RoboActivityGroup;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import roboguice.util.Ln;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TabHost;

import com.jtask.AppConstants;
import com.jtask.R;
import com.jtask.core.tasks.LoadTaskLists;
import com.mvp.BaseActivity;

@ContentView(R.layout.activity_main)
public class Main extends RoboActivityGroup implements BaseActivity,
		AppConstants {

	public static final int ADD_ACCOUNT_REQ_CODE = 19;
	private Executor executor = Executors.newSingleThreadExecutor();

	@InjectView(android.R.id.tabhost)
	private TabHost tabHost;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SharedPreferences pref = getSharedPreferences(JTASK_PREFERENCES,
				MODE_PRIVATE);
		if (pref.contains(K_ACCESS_TOKEN) && pref.contains(K_REFRESH_TOKEN)) {
			Ln.i("Loading previous info");
			executor.execute(new LoadTaskLists(this, null).future());
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.account_config:
			Ln.i("launching addAccount");
			startActivityForResult(new Intent(this, AddAccount.class),
					ADD_ACCOUNT_REQ_CODE);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (ADD_ACCOUNT_REQ_CODE == requestCode && RESULT_OK == resultCode) {
			String requestToken = data
					.getStringExtra(AppConstants.K_TOKEN_RESULT);
			if (!"".equals(requestToken))
				executor.execute(new LoadTaskLists(this, requestToken).future());
		} else
			super.onActivityResult(requestCode, resultCode, data);
	}

	public TabHost getTabHost() {
		return tabHost;
	}

}
